package com.zh.mediaservice.service.impl;

import com.zh.mediacommon.constant.JWTClaimsConstant;

import com.zh.mediacommon.constant.MessageConstant;
import com.zh.mediacommon.context.BaseContext;
import com.zh.mediacommon.ecxeption.UserException;
import com.zh.mediacommon.properties.JwtProperties;
import com.zh.mediacommon.util.AliMessageUtil;
import com.zh.mediacommon.util.CheckInformation;
import com.zh.mediacommon.util.JwtUtil;
import com.zh.mediacommon.util.VerifyCodeUtil;
import com.zh.mediapojo.dto.UserDto;
import com.zh.mediapojo.dto.UserPasswordDTO;
import com.zh.mediapojo.entity.User;
import com.zh.mediaservice.mapper.UserMapper;
import com.zh.mediaservice.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private AliMessageUtil aliMessageUtil;
    @Autowired
    private RedisTemplate redisTemplate;
    private static final Integer TIME=5;
    @Override
    public String insertUser(UserDto user) {
        log.info("注册用户", user);
        User user1=new User();
        if(!CheckInformation.isCharacterAndNumber(user.getPassword()))
            throw new UserException(MessageConstant.PASSWORD_ERROR);
        if(!CheckInformation.checkPassword(user.getPassword(),user.getConfirmPassword()))
            throw new UserException(MessageConstant.VERIFY_ERROR);
        if(user.getIdCard()!=null && !user.getIdCard().equals("")){
            if(!CheckInformation.isIDNumber(user.getIdCard()))
                throw new UserException(MessageConstant.ID_CARD_ERROR);
        }
        if (!CheckInformation.isValidPhoneNumber(user.getPhone()))
            throw new UserException(MessageConstant.PHONE_ERROR);
        BeanUtils.copyProperties(user,user1);
        String password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        String idCard = DigestUtils.md5DigestAsHex(user.getIdCard().getBytes());
        user1.setPassword(password);
        user1.setIdCard(idCard);
        userMapper.insertUser(user1);
        Map<String, Object> claims = new HashMap<>();
        claims.put(JWTClaimsConstant.USER_ID, user1.getId());
        log.info("jwt校验:{}", user1.getId());
        String token = JwtUtil.createJWT(jwtProperties.getSecretKey(), jwtProperties.getTtl(), claims);
        return token;
    }

    @Override
    public String log(String username, String password, HttpServletRequest request) {
        log.info("登录用户{}",username);
        User user= userMapper.selectByUsername(username);
        log.info("用户{}登录",username);
        if(user==null)
            throw new UserException(MessageConstant.USER_NOT_EXISTS);
        request.getSession().setAttribute("userId","0"+user.getId().toString());
        log.info("session对象存储{}",request.getSession());
        if(!user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes())))
            throw new UserException(MessageConstant.USER_PASSWORD_ERROR);
        Map<String, Object> claims = new HashMap<>();
        claims.put(JWTClaimsConstant.USER_ID, user.getId());
        log.info("jwt校验:{}", user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getSecretKey(), jwtProperties.getTtl(), claims);
        return token;
    }

    @Override
    public void updatePassword(UserPasswordDTO userPasswordDTO) {
        Long id= BaseContext.getCurrentId();
        String password = userMapper.selectPasswordById(id);
        if (!password.equals(DigestUtils.md5DigestAsHex(userPasswordDTO.getOldPassword().getBytes())))
            throw new UserException(MessageConstant.USER_PASSWORD_ERROR);
        if (userPasswordDTO.checkPassword())
            throw new UserException(MessageConstant.IS_EQUAL_PASSWORD);
        if(!CheckInformation.isCharacterAndNumber(userPasswordDTO.getNewPassword()))
            throw new UserException(MessageConstant.PASSWORD_ERROR);
        userMapper.updatePassword(id,DigestUtils.md5DigestAsHex(userPasswordDTO.getNewPassword().getBytes()));
    }

    /*
    * 获取用户详细信息
    *
    * */
    @Override
    public User getUserInfo() {
        Long id= BaseContext.getCurrentId();
        User user=userMapper.selectUserById(id);
        user.setPassword("*****");
        user.setIdCard("*********************");
        return user;
    }

    /*
    * 发送验证码
    * */
    @Override
    public String sendCode(String phoneNumber) {
        try {
            String code = VerifyCodeUtil.getCode();
            //注释的内容 -->阿里云短信服务
//            boolean agreed =  aliMessageUtil.sendSms(phoneNumber, code);
//            if(!agreed)
//                throw new UserException(MessageConstant.SEND_CODE_ERROR);
//            else{
                redisTemplate.opsForValue().set(phoneNumber,code,TIME, TimeUnit.MINUTES);
//            }
            return code;
        }catch (Exception e){
            throw new UserException(MessageConstant.SEND_CODE_ERROR);
        }
    }

    @Override
    public void resetPassword(String newPassword, String userName) {
        if(!CheckInformation.isCharacterAndNumber(newPassword))
                throw new UserException(MessageConstant.PASSWORD_ERROR);
//        Long id=BaseContext.getCurrentId();
        newPassword = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        User user = userMapper.selectByUsername(userName);
        if(user==null)
            throw new UserException(MessageConstant.USER_NOT_EXISTS);
        userMapper.updatePassword(user.getId(),newPassword);
    }

    @Override
    public User getChatUserInfo(Long userId) {
        User user = userMapper.selectUserById(userId);
        if(user==null)
            throw new UserException(MessageConstant.USER_NOT_EXISTS);
        return user;
    }
}
